import { useState } from 'react';

import './homeApp.css';
import { tcsStore, PIECES } from '../../store/TcsStore';

// 将 qilist 移到组件外部，避免每次渲染重新创建
// eslint-disable-next-line no-unused-vars
const QILIST_LENGTH = 9;

// 检查获胜条件的辅助函数
const calculateWinner = squares => {
  // 所有可能的获胜组合
  const winPatterns = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8], // 行
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8], // 列
    [0, 4, 8],
    [2, 4, 6], // 对角线
  ];

  // 检查每种获胜模式
  for (const pattern of winPatterns) {
    const [a, b, c] = pattern;
    if (squares[a] !== PIECES.EMPTY && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }

  return null; // 没有获胜者
};

function App() {
  const [userid, setUserid] = useState(1);

  const piece = tcsStore(state => state.piece || []);
  const lineLen = tcsStore(state => state.lines.length);
  const setPieceIndex = tcsStore(state => state.setPieceIndex);
  const chPiece = tcsStore(state => state.chPiece);
  const resetGame = tcsStore(state => state.resetGame);
  const winner = calculateWinner(piece);

  const setPiece = index => {
    // eslint-disable-next-line no-console
    console.log('点击位置:', index);
    if (piece[index] !== PIECES.EMPTY || winner) {
      return;
    }
    setPieceIndex(index, userid);
    // eslint-disable-next-line no-console
    console.log('piece:', piece);
    if (calculateWinner(piece.with(index, userid))) {
      alert(`${userid === 1 ? '玩家1 (X)' : '玩家2 (O)'} 获胜！`);
    }
    forUserid();
  };

  // 修复撤回按钮的点击事件
  const chClick = () => {
    if (lineLen > 0) {
      chPiece();
      forUserid();
    }
  };

  // 修改 chshow 函数，返回 null 而不是空字符串
  const chshow = () => {
    return lineLen > 0 ? <button onClick={chClick}>撤回</button> : null;
  };
  const reshow = () => {
    return winner ? <button onClick={resetGame}>重新开始</button> : null;
  };

  const forUserid = () => {
    setUserid(userid => (userid === 1 ? 2 : 1));
  };

  return (
    <>
      <div className="body">
        <div>井字棋</div>
        <div>当前用户: {userid === 1 ? '玩家1 (X)' : '玩家2 (O)'}</div>
        <div className="qipan">
          {piece.map((_, index) => {
            {
              return (
                <div key={`cell-${index}`}>
                  <button className={`qizi qizi${piece[index]}`} onClick={() => setPiece(index)}>
                    {piece[index] === PIECES.EMPTY
                      ? ''
                      : piece[index] === PIECES.PLAYER1
                        ? 'X'
                        : 'O'}
                  </button>
                </div>
              );
            }
          })}
        </div>
        <div>
          历史步数: {lineLen}
          {chshow()}
          {reshow()}
        </div>
      </div>
    </>
  );
}

export default App;
